package cn.haiway.drools.utils;

import lombok.extern.slf4j.Slf4j;
import org.drools.compiler.kie.builder.impl.InternalKieModule;
import org.kie.api.KieServices;
import org.kie.api.builder.KieBuilder;
import org.kie.api.builder.KieFileSystem;
import org.kie.api.builder.KieRepository;
import org.kie.api.builder.ReleaseId;
import org.kie.api.builder.model.KieBaseModel;
import org.kie.api.builder.model.KieModuleModel;
import org.kie.api.builder.model.KieSessionModel;
import org.kie.api.conf.EqualityBehaviorOption;
import org.kie.api.conf.EventProcessingOption;
import org.kie.api.runtime.conf.ClockTypeOption;

import java.util.ArrayList;
import java.util.List;

/**
 * @author Reyton Liu
 * @date 2019-04-21 21:25
 */
@Slf4j
public class KjarBuilderUtil {

    public static KieFileSystem createKieFileSystemWithKProject(KieServices ks, boolean isDefault, String kbaseName, String ksessionName) {
        KieModuleModel moduleModel = ks.newKieModuleModel();

        KieBaseModel kieBaseModel = moduleModel.newKieBaseModel(kbaseName).setDefault(isDefault)
                .setEqualsBehavior(EqualityBehaviorOption.EQUALITY)
                .setEventProcessingMode(EventProcessingOption.STREAM);

        kieBaseModel.newKieSessionModel(ksessionName).setDefault(isDefault)
                .setType(KieSessionModel.KieSessionType.STATEFUL)
                .setClockType(ClockTypeOption.get("realtime"));

        KieFileSystem kfs = ks.newKieFileSystem();
        kfs.writeKModuleXML(moduleModel.toXML());
        return kfs;
    }

    /**
     * 动态生成pom文件
     * @param releaseId
     * @param dependencies
     * @return
     */
    public static String createPom(ReleaseId releaseId, ReleaseId... dependencies) {
        String pom =
                "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
                        "<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n" +
                        "         xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd\">\n" +
                        "  <modelVersion>4.0.0</modelVersion>\n" +
                        "  <packaging>kjar</packaging>\n" +
                        "  <groupId>" + releaseId.getGroupId() + "</groupId>\n" +
                        "  <artifactId>" + releaseId.getArtifactId() + "</artifactId>\n" +
                        "  <version>" + releaseId.getVersion() + "</version>\n" +
                        "\n";
        if (dependencies != null && dependencies.length > 0) {
            pom += "<dependencies>\n";
            for (ReleaseId dep : dependencies) {
                pom += "<dependency>\n";
                pom += "  <groupId>" + dep.getGroupId() + "</groupId>\n";
                pom += "  <artifactId>" + dep.getArtifactId() + "</artifactId>\n";
                pom += "  <version>" + dep.getVersion() + "</version>\n";
                pom += "</dependency>\n";
            }
            pom += "</dependencies>\n" +
                    "<build>\n" +
                    "    <plugins>\n" +
                    "      <plugin>\n" +
                    "        <groupId>org.kie</groupId>\n" +
                    "        <artifactId>kie-maven-plugin</artifactId>\n" +
                    "        <version>7.19.0.Final</version>\n" +
                    "        <extensions>true</extensions>\n" +
                    "      </plugin>\n" +
                    "    </plugins>\n" +
                    "  </build>";
        }
        pom += "</project>";
        return pom;
    }


    /***
     * 构建KJar
     * @param kieServices kieServices
     * @param releaseId releaseId
     * @param kieFileSystem kieFileSystem
     * @return KJar的Byte数组
     */
    public static byte[] createKJar(KieServices kieServices, ReleaseId releaseId, KieFileSystem kieFileSystem) {
        KieBuilder kb = kieServices.newKieBuilder(kieFileSystem).buildAll();
        if (kb.getResults().hasMessages(org.kie.api.builder.Message.Level.ERROR)) {
            List<String> errors = new ArrayList<>();
            for (org.kie.api.builder.Message result : kb.getResults().getMessages()) {
                errors.add(result.getText());
            }
           log.error("error.kjarBuilder.buildErro:"+ errors.toString());
        }
        KieRepository kp = kieServices.getRepository();
        InternalKieModule kieModule = (InternalKieModule) kp.getKieModule(releaseId);
        return kieModule.getBytes();
    }
}
